package com.xuyh.pdf.utils.ttjspider;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;

import java.sql.SQLException;
import java.util.List;

/**
 * @author xuyh0817
 * @version 1.0.0
 * @email xuyh0817@foxmail.com
 * @date 2024/9/24 12:42
 * @doc
 * @website
 * @description todo
 */
public class InsertArticle {
    public void insert(Article article) throws SQLException {
        Long id = Db.use().insertForGeneratedKey(
                Entity.create("cms_article")
                        .set("type", article.getType())
                        .set("category_id", article.getCategoryId())
                        .set("title", article.getTitle())
                        .set("content", article.getContent())
                        .set("view_count", article.getViewCount())
                        .set("source", article.getSource())
                        .set("dept_id", article.getDeptId())
                        .set("dept_name", article.getDeptName())
                        .set("creator", article.getCreator())
                        .set("create_time", article.getCreateTime())
                        .set("updater", article.getUpdater())
                        .set("update_time", article.getUpdateTime())
                        .set("deleted", article.getDeleted())
                        .set("tenant_id", article.getTenantId())
        );

        article.setId(id);

        insertAttachment(article);
    }

    private void insertAttachment(Article article) throws SQLException {
        List<Attachment> attachments = article.getAttachments();
        if (CollUtil.isNotEmpty(attachments)) {
            for (Attachment attachment : attachments) {
                Db.use().insert(Entity.create("cms_article_attachment")
                        .set("attachment_id", attachment.getId())
                        .set("article_id", article.getId())
                );
            }
        }
    }
}
